/**
 *
 */
package com.elcom.emocbc.cbm;

import java.util.List;
import java.util.concurrent.SynchronousQueue;
import com.elcom.emocbc.db.CellBroadcastDAO;
import com.elcom.emocbc.dbmapping.persistence.ProgramBroadcastResultPersistance;
import com.elcom.emocbc.dbmapping.tables.pojos.ProgramBroadcastResult;
import java.sql.Timestamp;
import java.util.Date;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author tiamo114
 *
 */
public class BroadcastThread implements Runnable {

    private final Logger logger = LoggerFactory.getLogger(BroadcastThread.class);
    private CellBroadcastDAO dao = null;
    private SynchronousQueue<BroadcastDTO> q = null;

    /**
     * @param _q
     */
    public BroadcastThread(SynchronousQueue<BroadcastDTO> _q) {
        this.dao = new CellBroadcastDAO();
        this.q = _q;
    }

    @Override
    public void run() {
        try {
            logger.info("CellbroadCast is running!!!");

            List<BroadcastDTO> listBroadcast = dao.getListBroadcast();
            ProgramBroadcastResultPersistance programBroadcastResultDao = new ProgramBroadcastResultPersistance();
            for (BroadcastDTO broadcastDTO : listBroadcast) {
                try {
                    broadcastDTO = checkTriviaProgram(broadcastDTO);
                    String scheduleId = UUID.randomUUID().toString();
//                    broadcastDTO.setScheduleId(scheduleId);
                    this.q.offer(broadcastDTO);
                    logger.info("Zone {} - Time {} - Add Broadcast request into queue: {}", broadcastDTO.getZone(), broadcastDTO.getStartTime(), broadcastDTO.toString());

                    ProgramBroadcastResult result = new ProgramBroadcastResult();
                    result.setScheduleId(scheduleId);
                    result.setBroadcastTime(new Timestamp(broadcastDTO.getStartDate().getTime()));
                    result.setCpId(broadcastDTO.getCpTopicId());
                    result.setLastUpdatedTime(new Timestamp(new Date().getTime()));
                    result.setProgramId(broadcastDTO.getProgramID());
                    result.setProgramIndex(broadcastDTO.getIndex());
                    result.setTopicId(broadcastDTO.getTopicID());
                    result.setZoneId((long) broadcastDTO.getZoneID());
                    result.setBroadcastState("Pending");
                    result.setTopicName(broadcastDTO.getTopicName());
                    result.setSubcontent(broadcastDTO.getSubContent());
                    result.setCpName(broadcastDTO.getCpName());
                    result.setTotalCells(0);
                    result.setFailureCells(0);
                    result.setSuccessCells(0);
                    result.setPendingCells(0);
                    programBroadcastResultDao.insert(result);
                    logger.info("Zone {} - Time {} - Inserted blank ProgramBroadcastResult to DB: {}", broadcastDTO.getZone(), broadcastDTO.getStartTime(), result);
                } catch (Exception e) {
                    logger.error("", e);
                }
            }
        } catch (Exception ex) {
            logger.error("", ex);
        }
    }

    private BroadcastDTO checkTriviaProgram(BroadcastDTO broadcastDTO) {
        try {
            logger.info("Zone {} - Time {} - Checking if programId {} is Trivia...", broadcastDTO.getZone(), broadcastDTO.getStartTime(), broadcastDTO.getProgramID());
            String chainId = broadcastDTO.getChainId();
            if (chainId != null && !chainId.trim().isEmpty()) {
                logger.info("Zone {} - Time {} - ProgramId {} is Trivia with chain_id {}, so getting the first question...", broadcastDTO.getZone(), broadcastDTO.getStartTime(), broadcastDTO.getProgramID(), chainId);
                BroadcastDTO firstProgramOfTriviaChain = dao.getFirstProgramOfTriviaChain(chainId);
                if (firstProgramOfTriviaChain != null) {
                    broadcastDTO.setProgramID(firstProgramOfTriviaChain.getProgramID());
                    broadcastDTO.setIndex(firstProgramOfTriviaChain.getIndex());
                    broadcastDTO.setSubContent(firstProgramOfTriviaChain.getSubContent());
                    logger.info("Zone {} - Time {} - First Trivia question with chain_id {} is {}", broadcastDTO.getZone(), broadcastDTO.getStartTime(), chainId, broadcastDTO.getProgramID());
                }
            }
        } catch (Exception ex) {
            logger.error("", ex);
        }
        return broadcastDTO;
    }
}
